package com.tarry.aware;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

/**
 * Spring Aware的目的是为了让Bean获得Spring容器的服务。
 * 通过实现BeanNameAware接口来实现在bean加载时，得到bean的名称，
 * 通过实现ResourceLoaderAware接口，来获得在bean加载时，活动资源加载服务
 */
@Service
public class AwareService implements BeanNameAware,ResourceLoaderAware {

    private String beanName;
    private ResourceLoader loader;

    public AwareService(){
        System.out.println("create awareService bean");
    }

    public void setBeanName(String s) {
        System.out.println(" set bean name");
        this.beanName  = s;
    }


    public void setResourceLoader(ResourceLoader resourceLoader) {
        System.out.println("get the resourceLoader");
        this.loader = resourceLoader;
    }

    public void outputResult(){
        System.out.println("Bean name is " + beanName);
        Resource resource = loader.getResource("classpath:aware.txt");
        try {
            System.out.println("LoaderResource get the content is " + IOUtils.toString(resource.getInputStream()));
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
